<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Request;
use think\Paginator;
use think\paginator\driver\Bootstrap;
/**
 * 产品订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    // 订单列表
    public function index(){
        $order=db("order");
         //订单池订单
        $where1['status']=1;
        $where1['paystatus']=0;
        $where1['saleuser_id']=0;
        $orderPoolList=$order->where($where1)->order("id desc")->select();
        $count=count($orderPoolList);

        $curPage = input('get.pagelist') ? input('get.pagelist') : 1;//接收前段分页传值
        $listRow = 10;//每页2行记录
        $showdata = array_slice($orderPoolList, ($curPage - 1)*$listRow, $listRow,true);// 数组中根据条件取出一段值，并返回
        $p = Bootstrap::make($showdata, $listRow, $curPage, $count, false, [
            'var_page' => 'pagelist',
            'path'     => url("/admin/order/index"),//这里根据需要修改url
            'query'    => [],
            'fragment' => '',
        ]);
        $p->appends($_GET);
        $this->assign('pagelist', $p->render());






        //dump($orderPoolList);


        //销售的订单
        $admin=$_SESSION['think']['admin'];
        //dump($admin);
         $where['status']=1;
         $where['paystatus']=0;
        $where['saleuser_id']=$admin['id'];
         $orderList=$order->where($where)->order("id desc")->paginate(10);
        //dump($orderList);
        $page=$orderList->render();
        $item=$orderList->items();
        foreach($item as $k=>$v){
            $resList=db("order_pay")->field("price_c")->where("order_id=".$v['id']." and status<>3")->select();
            if(empty($resList)){
                $item[$k]['pay_list']='';
            }else{
                $item[$k]['pay_list']=$resList;
            }

        }
       $this->assign([
            'orderList'=>$item,
           'page'=>$page,
           'orderPoolList'=>$p,
           'count'=>$count,

        ]);
        return $this->view->fetch();

    }

    public function split_index(){

        $data=input("get.");
        $number=$data['installment'];
      
        $arr=[];
        for($i=0;$i<$number;$i++){
            $arr[$i]['number_id']=$i+1;
        }
        $orderRes=db("order")->find($data['id']);
        //dump($orderRes);
        if(Request()->isPost()){
            $pay_list=db("order_pay")->where("order_id",$data['id'])->select();
            foreach($pay_list as $k=>$v){
                db("order_pay")->delete($v['id']);
            }
            $dataPost=input("post.");
            foreach($dataPost as $k=>$v){
                $pay['order_id']=$data['id'];
                $pay['price_c']=$v;
                $pay['status']=0;
                $pay['rateid']=$orderRes['exrateid'];
                db("order_pay")->insert($pay);
            }
            // $date_time['e_time']=$number*86400+time();
            // db("order")->where("id",$data['id'])->update($date_time);

            $this->success("订单拆分成功","/admin/order/index");
        }

        $this->assign([
            'orderRes'=>$orderRes,
            'number'=>$number,
            'arr'=>$arr,
        ]);
        return $this->view->fetch();
    }


    public function claim(){
        if(Request()->isAjax()){
            $id=input("post.id");

            $result=db("order")->field("saleuser_id")->where("id",$id)->find();
            if($result['saleuser_id']>0){
                ajaxMsg("改订单已被认领请刷新页面重新选择",0);
            }
            $admin=$_SESSION['think']['admin'];
            $update['saleuser_id']=$admin['id'];
            $res=db("order")->where("id",$id)->update($update);

            if($res){
                ajaxMsg("订单认领成功",1);

            }else{
                ajaxMsg("订单认领失败",0);

            }


        }
    }


//修改自费项目页面
    public function order_supplement_list(){

        $orderid=input("order_id");

        $this->view->assign("orderid",$orderid);
        $supplement= db("order_supplement")->where("order_id=".$orderid." and fid=0")->select();

        $supplement_list = [];
        $supplement_coupon=0;
        $supplement_score=0;
        for($i=0;$i<count($supplement);$i++){

            if($supplement[$i]["os_type"]==1){
                $supplement_list[]=$supplement[$i];
            }
            if($supplement[$i]["os_type"]==2){
                $supplement_score=$supplement[$i]['tatolprice'];
            }
            if($supplement[$i]["os_type"]==3){
                $supplement_coupon=$supplement[$i]['tatolprice'];
            }

        }

        $this->view->assign("supplement_list",$supplement_list);
        $this->view->assign("supplement_coupon",$supplement_coupon);
        $this->view->assign("supplement_score",$supplement_score);


        $order=db("order")->where("id=".$orderid)->find();


        $productinfo=db("product")->where(["id"=>$order['p_id']])->find();
        $this->view->assign("productinfo", $productinfo);
        $orderinfoarr=db("order_info")->where(["order_id"=>$orderid])->select();
        //判断是否有折扣
        $discount=0;
        //定义总人数
        $tournum=0;

        // 定义 折后基本团费页面需要--计算折后基本团费

        $discount_baseprice_total=0;

        for($i=0;$i<count($orderinfoarr);$i++){

            $discount=$orderinfoarr[$i]["discount"];
            if($orderinfoarr[$i]["discount"]!=0){
                $discount =$orderinfoarr[$i]["discount"];
            }
            $packageinfo=db("product_package")->where(["id"=>$orderinfoarr[$i]['package_id']])->find();
            $orderinfoarr[$i]['packageinfo']=$packageinfo;
            $orderhouseinfoarr=db("order_house")->where(["order_info_id"=>$orderinfoarr[$i]['id']])->select();

            $orderinfoarr[$i]['houseinfo']=$orderhouseinfoarr;
            //计算总人数
            for($j=0;$j<count($orderhouseinfoarr);$j++){
                $tournum=$tournum+$orderhouseinfoarr[$j]['pnum'];
                $discount_baseprice_total=$discount_baseprice_total+$orderhouseinfoarr[$j]['payprice'];
            }

        }


        $this->view->assign("discount_baseprice_total", $discount_baseprice_total);

        $order['orderinfo']=$orderinfoarr;

        //封装自费产品
        $selfpayid=0;
        $selfpayid=db("product_group")->field("selfpay_id")->where(["id"=>$order['orderinfo']['0']['group_id']])->find();

        $selfpayinfo=[];
        if(isset($selfpayid['selfpay_id'])){
            $selfpayid=$selfpayid['selfpay_id'];
            $selfpayinfo=db("product_selfpay")->where(["id"=>$selfpayid])->find();
            $selfpayinfo["spitem"]=db("product_selfpay")->where(["fid"=>$selfpayinfo['id']])->select();
            if ($selfpayinfo["spitem"]){
                for($i=0;$i<count($selfpayinfo["spitem"]);$i++){
                    $selfpayinfo["spitem"][$i]['spgroup']=db("product_selfpay")->where(["fid"=>$selfpayinfo["spitem"][$i]['id']])->select();
                    if($selfpayinfo["spitem"][$i]['spgroup']){
                        for($j=0;$j<count($selfpayinfo["spitem"][$i]['spgroup']);$j++){
                            $selfpayinfo["spitem"][$i]['spgroup'][$j]['sp']=db("product_selfpay")->where(["fid"=>$selfpayinfo["spitem"][$i]['spgroup'][$j]['id']])->select();

                            if($selfpayinfo["spitem"][$i]['spgroup'][$j]['sp']){

                                for($k=0;$k<count($selfpayinfo["spitem"][$i]['spgroup'][$j]['sp']);$k++){
                                    $selfpayinfo["spitem"][$i]['spgroup'][$j]['sp'][$k]['spprice']=db("product_spprice")->where(["sp_id"=>$selfpayinfo["spitem"][$i]['spgroup'][$j]['sp'][$k]['id']])->select();
                                }
                            }
                        }
                    }
                }
            }
        }

//dump($selfpayinfo);



        //用户优惠卷

        $where=[];
        $where['userid']=['eq',$this->auth->id];
        $where['status']=['eq',0];
        $usercoupon= db("user_coupon")->where($where)->select();

        $usercouponinfoarr=[];
        for($i=0;$i<count($usercoupon);$i++){
            $couponinfoselect="";
            $where=[];
            $where['id']=['eq',$usercoupon[$i]['coupon_id']];
            $where['status']=['eq',0];
            $where['end_time']=['lt',time()];
            $couponinfo=db("coupon")->where($where)->find();

            //所有产品可用
            if($couponinfo["producttype"]==0){
                $couponinfoselect=$usercoupon[$i];
            }
            //查找指定产品，判断是否与当前产品匹配
            if($couponinfo["producttype"]==1){
                $couponproductinfo=db("coupon_product")->where(["coupon_id"=>$usercoupon[$i]['coupon_id'],"product_id"=>$productinfo['id']])->find();
                if($couponproductinfo){
                    $couponinfoselect=$usercoupon[$i];
                }
            }
            //判断有折扣是否可用
            if($couponinfo['discounttype']==1&&$discount!=0){
                $couponinfoselect="";
            }
            if($couponinfoselect!=""){
                $usercouponinfoarr[]= $couponinfoselect;
            }

        }

        $this->view->assign("usercoupon", $usercouponinfoarr);

        //用户积分
        $userscore=$this->auth->score;
        $this->view->assign("userscore", $userscore);
        //用户人数
        $this->view->assign("tournum", $tournum);

        //自费项目
        $this->view->assign("selfpayinfo", $selfpayinfo);
        $this->view->assign("order", $order);
        $productinfo=db("product")->where(["id"=>$order['p_id']])->find();
        $this->view->assign("productinfo", $productinfo);
        return $this->view->fetch();
    }



    //管理员维护自费项目
    function order_supplement_edit(){

        $orderid=input("orderid");
        $selfpaylist=input("selfpaylist");
        $order=db("order")->where("id=".$orderid)->find();



        //删除原有自费项目

        db("order_supplement")->where("order_id=".$orderid." and os_type=1")->delete();

        //插入自费项目
        $sp =[];
        if($selfpaylist!=""){

            dump($selfpaylist);

            $sp = explode("*", $selfpaylist);
            for($i=0;$i<count($sp);$i++){
                $sp[$i]= explode("|",$sp[$i]);
            }
            for($i=0;$i<count($sp);$i++){
//0产品自费项目id|1自由行产品id|2自由行产品套餐id|3显示标题|4单价|5数量|6总数量|7总价|8儿童数量|9儿童单价
                $supplement=[];
                $supplement['fid']=0;
                $supplement['order_id']=$orderid;
                $supplement['spitem_id']=$sp[$i][0];
                $supplement['pro_id']=$sp[$i][1];
                $supplement['package_id']=$sp[$i][2];
                $supplement['title']=$sp[$i][3];
                $supplement['pay_time']=time();
                $supplement['unitprice']=$sp[$i][4];
                $supplement['num']=$sp[$i][5];
                $supplement['tatolprice']=$sp[$i][7];
                $supplement['os_type']=1;
                $supplement['paytype']=0;
                $supplement['userid']=$_SESSION['think']['admin']['id'];
                $supplement['username']=$_SESSION['think']['admin']['username'];
                $supplement['usertype']=1;
                $supplement['status']=0;
                $supplement['u_time']=time();
                //后期需要加入同业佣金计算
                $supplement['payprice']=$sp[$i][7];

                dump($supplement);
                //累计总额
               // $order_payprice=$order_payprice+$supplement['payprice'];
                db('order_supplement')->insert($supplement);
            }
        }


        //计算基础团费（含折扣）--用于总额修改
        $orderinfoarr=db("order_info")->where(["order_id"=>$orderid])->select();
        $discount_baseprice_total=0;

        for($i=0;$i<count($orderinfoarr);$i++){
            $packageinfo=db("product_package")->where(["id"=>$orderinfoarr[$i]['package_id']])->find();
            $orderinfoarr[$i]['packageinfo']=$packageinfo;
            $orderhouseinfoarr=db("order_house")->where(["order_info_id"=>$orderinfoarr[$i]['id']])->select();
            $orderinfoarr[$i]['houseinfo']=$orderhouseinfoarr;
            //计算总人数
            for($j=0;$j<count($orderhouseinfoarr);$j++){
               // $tournum=$tournum+$orderhouseinfoarr[$j]['pnum'];
                $discount_baseprice_total=$discount_baseprice_total+$orderhouseinfoarr[$j]['payprice'];
            }
        }


        //计算剩余补充项目金额（ + 积分抵扣 + 优惠卷   - 其他优惠）--用于总额修改
        $supplement_total=0;
       $supplement= db("order_supplement")->where("order_id=".$orderid." and status=0")->select();

for($i=0;$i<count($supplement);$i++){
    if($supplement[$i]['paytype']==0){
        $supplement_total=$supplement_total+$supplement[$i]['payprice'];
    }
    if($supplement[$i]['paytype']==1){
        $supplement_total=$supplement_total-$supplement[$i]['payprice'];
    }

}

    $pay_tatol=$supplement_total+$discount_baseprice_total;




//更新订单主表

        db("order")->where('id='.$orderid)->update(['payprice' => $pay_tatol]);
        //修改原支付表状态为失效
        db("order_pay")->where('order_id='.$orderid)->update(['status' => 3]);
        //生成新的支付表
     $order_pay=[];

        $order_pay['order_id']=$orderid;
        $order_pay['rateid']=$order['exrateid'];
        $order_pay['price_c']=$pay_tatol;
        $order_pay['status']=0;
        $order_pay['ctime']=time();
        db("order_pay")->insert($order_pay);

        $this->redirect('/admin/order');

    }

    //管理员回收（删除）订单


    function deleteorder(){
        $orderid=input("orderid");
        db("order")->where('id='.$orderid)->update(['status' => 5]);
        $this->redirect('/admin/order');
    }

    //订单增加金额或减少金额（不受控）

    function order_reduced(){

        $orderid=input("orderid");

        $action=input("action");


        if($action=="add"){
            $remark=input("remark");
            $tatolprice=input("tatolprice");
            $paytype=input("paytype");
            $title=input("title");
            //增加记录
            $supplement=[];
            $supplement['fid']=0;
            $supplement['order_id']=$orderid;
            $supplement['title']=$title;
            $supplement['remark']=$remark;
            $supplement['pay_time']=time();
            $supplement['tatolprice']=$tatolprice;
            $supplement['os_type']=5;
            $supplement['paytype']=$paytype;
            $supplement['userid']=$_SESSION['think']['admin']['id'];
            $supplement['username']=$_SESSION['think']['admin']['username'];
            $supplement['usertype']=1;
            $supplement['status']=0;
            $supplement['payprice']=$tatolprice;


            db("order_supplement")->insert($supplement);

            //修改订单总额
if($paytype==0){
    db("order")-> where("id=".$orderid)->setInc('payprice',$tatolprice);
}
if($paytype==1){
    db("order")-> where("id=".$orderid)->setDec('payprice',$tatolprice);
}
            //修改支付表，将原支付表设置为失效并生成新的支付表
          $order= db("order")->where('id='.$orderid)->find();

            //修改原支付表状态为失效
            db("order_pay")->where('order_id='.$orderid)->update(['status' => 3]);
            //生成新的支付表
            $order_pay=[];

            $order_pay['order_id']=$orderid;
            $order_pay['rateid']=$order['exrateid'];
            $order_pay['price_c']=$order['payprice'];
            $order_pay['status']=0;
            $order_pay['ctime']=time();
            db("order_pay")->insert($order_pay);
        }

        if($action=="del"){
            $supplementid=input("supplementid");
            $paytype=input("paytype");
            $tatolprice=input("tatolprice");
            db("order_supplement")->where("id=".$supplementid)->delete();
            //修改订单总额
            if($paytype==0){
                db("order")-> where("id=".$orderid)->setDec('payprice',$tatolprice);
            }
            if($paytype==1){
                db("order")-> where("id=".$orderid)->setInc('payprice',$tatolprice);
            }
            //修改支付表，将原支付表设置为失效并生成新的支付表
            $order= db("order")->where('id='.$orderid)->find();

            //修改原支付表状态为失效
            db("order_pay")->where('order_id='.$orderid)->update(['status' => 3]);
            //生成新的支付表
            $order_pay=[];

            $order_pay['order_id']=$orderid;
            $order_pay['rateid']=$order['exrateid'];
            $order_pay['price_c']=$order['payprice'];
            $order_pay['status']=0;
            $order_pay['ctime']=time();
            db("order_pay")->insert($order_pay);


        }


        $supplement= db("order_supplement")->where("order_id=".$orderid." and status=0 and os_type=5")->select();


        $this->assign("supplement",$supplement);
        $this->assign("orderid",$orderid);
        //$this->redirect('/admin/order/order_reduced');
        return $this->view->fetch();


    }



    //订单延迟

    public function delay(){
        if(request()->isAjax()){
            $data=input("post.");
            $id=$data['id'];
            $delay=$data['delay'];
            $order=db("order")->find($id);
            $time=$delay*86400;
            $update=$order['e_time']+$time;
            $updateData['e_time']=$update;
            $result=db("order")->where("id",$id)->update($updateData);
            if($result){
                ajaxMsg("延期时间修改成功",1);
            }else{
                ajaxMsg("延期时间修改失败",0);
            }
        }
    }



}
